import { Metadata } from "next";
import { createServerClient } from "~/trpc/server-client";
import { redirect, notFound } from "next/navigation";
import { auth } from "~/server/auth";
import { TRPCError } from "@trpc/server";
import { PageContainer } from "~/components/common/PageContainer";
import { JoinCourse } from "./components/JoinCourse";
import { Suspense } from "react";
import { Loading } from "~/components/common/Loading";
import { ErrorBoundary } from "~/components/common/ErrorBoundary";
import type { CourseInvitation, Course, User } from "@prisma/client";

interface Props {
  params: { id: string };
}

export const metadata: Metadata = {
  title: "加入课程 - 在线教育平台",
};

// 处理异步数据的组件
async function InvitationContent({ 
  promise 
}: { 
  promise: Promise<CourseInvitation & {
    course: Course & {
      teacher: Pick<User, "id" | "name">;
    };
  }>
}) {
  const invitation = await promise;
  
  if (!invitation || invitation.expiresAt < new Date()) {
    redirect(`/courses/join/error?type=expired`);
  }

  return (
    <PageContainer
      title="加入课程"
      description="您已收到课程邀请，请确认是否加入"
    >
      <JoinCourse invitation={invitation} />
    </PageContainer>
  );
}

export default async function JoinCoursePage({ params }: Props) {
  const session = await auth();
  
  if (!session) {
    const callbackUrl = encodeURIComponent(`/courses/join/invitation/${params.id}`);
    redirect(`/login?callbackUrl=${callbackUrl}`);
  }

  try {
    const trpc = await createServerClient();
    
    return (
      <ErrorBoundary>
        <Suspense fallback={<Loading />}>
          <InvitationContent 
            promise={trpc.courses.getInvitation.fetch({ 
              invitationId: params.id 
            })} 
          />
        </Suspense>
      </ErrorBoundary>
    );
  } catch (error) {
    if (error instanceof TRPCError) {
      let errorType = 'default';
      
      switch (error.code) {
        case 'NOT_FOUND':
          errorType = 'invalid';
          break;
        case 'BAD_REQUEST':
          if (error.message.includes('过期')) {
            errorType = 'expired';
          } else if (error.message.includes('最大使用次数')) {
            errorType = 'max-uses';
          } else if (error.message.includes('已经加入')) {
            errorType = 'already-joined';
          }
          break;
      }
      
      redirect(`/courses/join/error?type=${errorType}`);
    }
    
    notFound();
  }
}
